package com.igeek.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.config.AlipayConfig;
import com.igeek.domain.*;
import com.igeek.service.Orderservice;
import com.sun.org.apache.bcel.internal.generic.NEW;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@WebServlet("/order")
public class OrderServlet extends BaseServlet {
    public void ordersubmit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //假设登录后存在一个user对象
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            session.setAttribute("url","cart.jsp");
            response.sendRedirect("login.jsp");
            return;
        }
        //获取oid
        String oid = UUID.randomUUID().toString();
        Cart cart = (Cart) session.getAttribute("cart");
        //获取total
        double total = cart.getTotal();
        Order order = new Order(oid, total, user);
        List<OrderItem> orderItems = new ArrayList<>();
        Map<String, CartItem> cartItemMap = cart.getCartItems();
        for (Map.Entry<String, CartItem> entry : cartItemMap.entrySet()) {
            String itemid = UUID.randomUUID().toString();
            CartItem cartItem = entry.getValue();
            int count = cartItem.getBuyNum();
            double subtotal = cartItem.getSubTotal();
            Product product = cartItem.getProduct();
            OrderItem orderItem = new OrderItem(itemid, count, subtotal, product, order);
            orderItems.add(orderItem);
        }
        order.setOrderItems(orderItems);
        Orderservice service = new Orderservice();
        service.save(order);
        System.out.println(order);
        session.setAttribute("order", order);
        response.sendRedirect("order_info.jsp");
    }


    public void orderconfirm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //支付
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String oid = request.getParameter("oid");
        //付款金额，必填
        String total_amount = request.getParameter("total_amount");
        //订单名称，必填
        String subject = "testOrder";
        //商品描述，可空
        String body = "testBody";
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ oid +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        try {
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            response.getWriter().write(result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        String address =request.getParameter("address");
        String name =request.getParameter("name");
        String telephone =request.getParameter("telephone");
        Order order=new Order(oid,address,name,telephone);
        Orderservice service =new Orderservice();
        service.update(order);
        System.out.println(order.getAddress()+"-"+order.getName()+"-"+order.getTelephone());
    }


    public void myorder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //用户是否登录
        User user= (User) request.getSession().getAttribute("user");
        if (user==null){
            request.getSession().setAttribute("url","order?method=myorder");
            response.sendRedirect("login.jsp");
            return;
        }
        Orderservice service =new Orderservice();
        List<Order> orderList =service.findAllorder(user.getUid());
        request.setAttribute("order",orderList);
        request.getRequestDispatcher("order_list.jsp").forward(request,response);
    }

    public void getorderOid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nowPage = request.getParameter("nowPage");
        int page=1;
        if(nowPage == null){
            page =1;
        }else{
            page = Integer.parseInt(nowPage);
        }
        Orderservice service =new Orderservice();
        Pagination<Order> pagination=service.getPageData(page,8);
        request.setAttribute("page",page);
        request.setAttribute("list",pagination);
        request.getRequestDispatcher("order_list.jsp").forward(request,response);
    }
}